#define _DEFAULT_SOURCE
#include "lcd.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#define SCREEN_W 800
#define SCREEN_H 480
int fd = -1;//显示屏，描述符
static short* p = NULL;//指向显示屏的映射空间

//画点
//x=像素所在的行
//y=像素所在的列
//color颜色值

//int draw_small(int x, int y, short color)
//{
//
//
//
//}


void draw_point(int x, int y, short color)
{
    if (x < 0 || y < 0 || x >=480 || y >= 800)
    {
        return;
    }
    *(p+x*800+y) = color;
}

void draw_rect(int x0, int y0, int w, int h, short color)
{

    //画图显示纯色
    for(int i = 0; i < h; i++)// 纵坐标
    {
        for(int j = 0; j < w; j++)//横坐标
        {
            draw_point(i, j, color);
        }
    }
}
int display_bmp(char*bmp_filename)
{
    //打开bmp文件
    int bmp_fd = open(bmp_filename, O_RDWR);
    if(bmp_fd == -1)
    {
        perror("open bmp error:");
        return -1;
    }
    //读取数据:魔数
    char buf[2];
    read(bmp_fd, buf,2);
    if(buf[0] != 'B' || buf[1] != 'M')
    {
        printf("No\n");
        close(bmp_fd);
        return -1;
    }
    //printf("Yes\n");

    //宽
    //char data_buf[4];
    int w,h;
    lseek(bmp_fd, 0x12, SEEK_SET);
    read(bmp_fd,&w, 4);

    //高
    read(bmp_fd,&h, 4);

    //色深
    short depth = 0;
    lseek(bmp_fd, 0x1c, SEEK_SET);
    read(bmp_fd,&depth, 2);

    printf("%d*%d %hd\n", w, h, depth);

    //读取bmp文件颜色数据
    lseek(bmp_fd, 0x36, SEEK_SET);

    unsigned char bmp_color_data[ w*h*depth/8];
    read(bmp_fd, bmp_color_data, w*h*depth/8);

    close(bmp_fd);

    //显示bmp图片：
    // 从BMP颜色数组中，获取三个字节合成一个LCD的颜色数据，

    unsigned char*bmp_p = bmp_color_data;
    for (int i = 0; i < h; i++)
    {
        for (int j = 0; j < w; j++)
        {
            unsigned char r,g,b;
            b = *bmp_p++;
            g = *bmp_p++;
            r = *bmp_p++;

            short color = (b >> 3)& 0x1f | ((g >> 2)&0x3f) << 5 | ((r >> 3)&0x1f) << 11;
            draw_point(h - 1 - i, j, color);
        }
    }

    return 0;
}

int open_screen()
{
     //打开LCD文件
    fd = open("/dev/fb0", O_RDWR);
    if(fd == -1)
    {
        perror("open fb0 error:");
        return -1;
    }


    //映射
    p = mmap(NULL, 800 * 480 * 2, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (p == MAP_FAILED)
    {
        perror("");
        return -1;
    }
    return 0;
}
   
void close_screen()
{
    //解映射
    munmap(p, 800 * 480 * 2);

    //关闭LCD文件
    close(fd);
}
